package com.ck.hxc.config;
 
import com.alibaba.fastjson2.JSON;
import com.ck.hxc.entity.SysUser;
import com.ck.hxc.service.SysUserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
 
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private SysUserService userService;
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("X-Token");
        if(token!=null){
            try {
                String username = jwtUtils.parseToken(token, SysUser.class).getUserName();
                SysUser user=userService.lambdaQuery().eq(SysUser::getUserName,username).one();
                // 把业务数据存储到ThreadLocal（ThreadLocal 线程安全，能实现数据共享）
                ThreadLocalUtils.set(user);
                return true;
            } catch (Exception e) {
                log.error(e.toString());
            }
        }
        log.debug(request.getRequestURI()+" 验证token失败，禁止访问");
        response.setContentType("application/json;charset=utf-8");
        //response.getWriter().write(JSON.toJSONString(Result.failed(("Token无效，请重新登录")));
        return false;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtils.remove();
    }
}